package com.knirirr.beecountclassic;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout;
import android.os.Environment; 
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.File;


public class ListprojActivity extends Activity //implements OnItemClickListener
{
  // database access is needed in order to create the new project and 
  // write it to the database
  // N.B. after creating it, re-direct to an AddcountActivity to add the counts
  TextView listprojTitle;
  DbHelper dbHelper;
  Cursor cursor;
  ListView listProj;
  SQLiteDatabase db;
  CountAdapter adapter;
  Typeface font;
  ActionBar actionBar;
  static final String[] FROM = {DbHelper.P_NAME, DbHelper.P_CREATED_AT};
  static final int[] TO = {R.id.textProject, R.id.textCreatedAt};
  static String TAG = "BeeCount"; 
  AlertDialog alert;
  boolean mExternalStorageAvailable = false;                                                                              
  boolean mExternalStorageWriteable = false;                                                                              
  String state = Environment.getExternalStorageState();                                                                   
  SharedPreferences prefs;
  Boolean fontPref;
  File infile;
  File outfile;


  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    if (android.os.Build.VERSION.SDK_INT < 11)
    {
      setTheme(android.R.style.Theme_NoTitleBar);
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listproj);
    listProj = (ListView) findViewById(R.id.listProj);

    // background
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String backgroundPref = prefs.getString("pref_back", "default");
    fontPref = prefs.getBoolean("pref_font", true);
    String pictPref = prefs.getString("imagePath", "");

    LinearLayout layout = (LinearLayout) findViewById(R.id.listprojScreen);
    if (backgroundPref.equals("none"))
    {
       // boring black screen
    }
    else if (backgroundPref.equals("custom"))
    {
      if (!(pictPref.equals(""))) 
      {
        if (new File(pictPref).isFile())
        {
          layout.setBackgroundDrawable(BackgroundImage.decodeSampledBitmapFromResource(pictPref,ListprojActivity.this));
        }
        else
        {
          Toast.makeText(this,getString(R.string.customMissing),Toast.LENGTH_SHORT).show();
          layout.setBackgroundResource(R.drawable.beecount_knitting);
        }
      }
      else
      {
        Toast.makeText(this,getString(R.string.customNotDefined),Toast.LENGTH_SHORT).show();
        layout.setBackgroundResource(R.drawable.beecount_knitting);
      }
    }
    else if (backgroundPref.equals("default"))
    {
      layout.setBackgroundResource(R.drawable.beecount_knitting);
    } 



    // fancy fonts again
    if (fontPref == true)
    {
      font = Typeface.createFromAsset(getAssets(), "village.ttf"); 
      listprojTitle = (TextView) findViewById(R.id.listprojTitle);
      listprojTitle.setTypeface(font);
    }

    listProj.setOnItemClickListener(new OnItemClickListener()
    {
      @Override
      public void onItemClick(AdapterView<?> arg0, View view,int position, long id) 
      {
        //Take action here.
        Cursor cursor = (Cursor) listProj.getItemAtPosition(position);
        cursor.moveToPosition(position);
        long projId = cursor.getLong(cursor.getColumnIndex(DbHelper.P_ID));
        String projName = cursor.getString(cursor.getColumnIndex(DbHelper.P_NAME));
        Intent intent = new Intent(ListprojActivity.this, CountingActivity.class);
        intent.putExtra("projId",projId);
        intent.putExtra("projName",projName);
        startActivity(intent);
      }
    });

    dbHelper = new DbHelper(this);
    db = dbHelper.getReadableDatabase();
    Log.i("Beecount", "List Count");
  }


  @Override
  protected void onDestroy()
  {
    super.onDestroy();
    db.close();
  }

  @Override
  @SuppressWarnings("deprecation")
  protected void onResume()
  {
    super.onResume();
    cursor = db.query(DbHelper.PROJ_TABLE, null,null,null,null,null,DbHelper.P_CREATED_AT + " DESC");
    startManagingCursor(cursor);

    adapter = new CountAdapter(this,cursor,fontPref);
    listProj.setAdapter(adapter);
  }

  @Override
  @TargetApi(14)
  public boolean onCreateOptionsMenu(Menu menu)
  {                                                                                                                     
    MenuInflater inflater = getMenuInflater();                                                                          
    inflater.inflate(R.menu.listprojmenu, menu);                                                                                
    if (android.os.Build.VERSION.SDK_INT > 13)
    {
      actionBar = getActionBar();                                                                                         
      actionBar.setHomeButtonEnabled(true);                                                                               
    }
    return true;                                                                                                        
  }    

  public boolean onOptionsItemSelected(MenuItem item)
  {
    switch (item.getItemId())
    {
      case R.id.newProj:
        startActivity(new Intent(this, NewprojActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
        break;
      case R.id.exportMenu:
        exportDb();
        break;
      case R.id.importMenu:
        importDb();
        break;
      case android.R.id.home:                                                                                           
        startActivity(new Intent(this, WelcomeActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));                
        break;     
      default:
        return super.onOptionsItemSelected(item);
    }
    return true;
  }
  
    /*
   * export the beecount database, copying the entire file to the sdcard
   */
  @SuppressLint("SdCardPath")
  public void exportDb()
  {
    boolean mExternalStorageAvailable = false;                                                                              
    boolean mExternalStorageWriteable = false;                                                                              
    String state = Environment.getExternalStorageState();                                                                   
    File outfile = new File(Environment.getExternalStorageDirectory() + "/beecount.db");
    String destPath = "/data/data/com.knirirr.beecount/files";
    //File infile = new File("/data/data/com.knirirr.beecount/databases/beecount.db");
    try
    {
      destPath = getFilesDir().getPath();
    }
    catch (Exception e)
    {
      Log.e(TAG,"destPath error: " + e.toString());
    }
    destPath = destPath.substring(0, destPath.lastIndexOf("/")) + "/databases";
    File infile = new File(destPath + "/beecount.db");

    if (Environment.MEDIA_MOUNTED.equals(state))                                                                            
    {                                                                                                                       
      // We can read and write the media                                                                                    
      mExternalStorageAvailable = mExternalStorageWriteable = true;                                                         
    }                                                                                                                       
    else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))                                                             
    {                                                                                                                       
      // We can only read the media                                                                                         
      mExternalStorageAvailable = true;                                                                                     
      mExternalStorageWriteable = false;                                                                                    
    }                                                                                                                       
    else                                                                                                                    
    {                                                                                                                       
      // Something else is wrong. It may be one of many other states, but all we need                                       
      //  to know is we can neither read nor write                                                                          
      mExternalStorageAvailable = mExternalStorageWriteable = false;                                                        
    }                                                                                                                       

    if ((mExternalStorageAvailable == false) || ( mExternalStorageWriteable == false))                                      
    {                                                                                                                       
      Log.e(TAG,"No sdcard access");                                                                                        
      Toast.makeText(this,getString(R.string.noCard),Toast.LENGTH_SHORT).show(); 
      return;
    }    
    else
    {
      // export the db
      try 
      {
        copy(infile, outfile);
        Toast.makeText(this,getString(R.string.saveWin),Toast.LENGTH_SHORT).show(); 
        return;
      }
      catch (IOException e)
      {
        Log.e(TAG,"Failed to copy database");                                                                                        
        Toast.makeText(this,getString(R.string.saveFail),Toast.LENGTH_SHORT).show(); 
        return;
      }

    }
  }

  /*
   * copy in a new version of the beecount db from elsewhere
   */
  @TargetApi(5)
  @SuppressLint("SdCardPath")
  public void importDb()
  {
    infile = new File(Environment.getExternalStorageDirectory() + "/beecount.db");
    //outfile = new File("/data/data/com.knirirr.beecount/databases/beecount.db");
    String destPath = "/data/data/com.knirirr.beecount/files";
    try
    {
      destPath = getFilesDir().getPath();
    }
    catch (Exception e)
    {
      Log.e(TAG,"destPath error: " + e.toString());
    }
    destPath = destPath.substring(0, destPath.lastIndexOf("/")) + "/databases";
    //File infile = new File(destPath + "/beecount.db");
    //outfile = new File(this.getFilesDir().getPath() + "/data/com.knirirr.beecount/databases/beecount.db");
    outfile = new File(destPath + "/beecount.db");
    if(!(infile.exists()))
    {
      Toast.makeText(this,getString(R.string.noDb),Toast.LENGTH_SHORT).show(); 
      return;
    }

    // a confirm dialogue before anything else takes place
    // http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog
    // could make the dialog central in the popup - to do later
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setIcon(android.R.drawable.ic_dialog_alert);
    builder.setMessage(R.string.confirmImport).setCancelable(false).setPositiveButton(R.string.importButton, new DialogInterface.OnClickListener()
    {
      public void onClick(DialogInterface dialog, int id)
      {
        // START
        // replace this with another function rather than this lazy c&p
        if (Environment.MEDIA_MOUNTED.equals(state))
        {
          // We can read and write the media
          mExternalStorageAvailable = mExternalStorageWriteable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
        {
          // We can only read the media
          mExternalStorageAvailable = true;
          mExternalStorageWriteable = false;
        } else
        {
          // Something else is wrong. It may be one of many other states, but all we need
          //  to know is we can neither read nor write
          mExternalStorageAvailable = mExternalStorageWriteable = false;
        }


        if ((mExternalStorageAvailable == false) || (mExternalStorageWriteable == false))
        {
          Log.e(TAG, "No sdcard access");
          Toast.makeText(ListprojActivity.this, getString(R.string.noCard), Toast.LENGTH_SHORT).show();
          return;
        } else
        {
          try
          {
            copy(infile, outfile);
            Toast.makeText(ListprojActivity.this, getString(R.string.importWin), Toast.LENGTH_SHORT).show();
            db.close();
            Intent intent = getIntent();
            if (android.os.Build.VERSION.SDK_INT > 4)
            {
              overridePendingTransition(0, 0);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            finish();
            if (android.os.Build.VERSION.SDK_INT > 4)
            {
              overridePendingTransition(0, 0);
            }
            startActivity(intent);
          } catch (IOException e)
          {
            Log.e(TAG, "Failed to import database");
            Toast.makeText(ListprojActivity.this, getString(R.string.importFail), Toast.LENGTH_SHORT).show();
            return;
          }
        }

        // END
      }
    }).setNegativeButton(R.string.importCancelButton, new DialogInterface.OnClickListener()
    {
      public void onClick(DialogInterface dialog, int id)
      {
        dialog.cancel();
      }
    });
    alert = builder.create();
    alert.show();
  }

  // http://stackoverflow.com/questions/9292954/how-to-make-a-copy-of-a-file-in-android
  public void copy(File src, File dst) throws IOException 
  {
    FileInputStream in = new FileInputStream(src);
    FileOutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) 
    {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
  }
}
